package com.crazymakercircle.loadbalance;

import java.util.List;
public class WeightedRoundRobinBalancer {
    private List<Server> servers; //服务列表
    private int totalWeight; //总权重

    public WeightedRoundRobinBalancer(List<Server> servers) {
        this.servers = servers;
        // 初始化总权重
        this.totalWeight = servers.stream().mapToInt(Server::getWeight).sum();
        System.out.println("totalWeight = " + totalWeight);
    }
    
    // 获取当前轮询中要选择的服务器
    public Server doSelect() {
        Server selectedServer = null;

        for (Server server : servers) {
            // 增加当前权重
            server.setCurrentWeight(server.getCurrentWeight() + server.getWeight());
            // 选择 currentWeight 最大的服务器
            if (selectedServer == null || server.getCurrentWeight() > selectedServer.getCurrentWeight()) {
                selectedServer = server;
            }
        }
        // 将选择的服务器 currentWeight 减去总权重
        if (selectedServer != null) {
            selectedServer.setCurrentWeight(selectedServer.getCurrentWeight() - totalWeight);
        }
        selectedServer.usedOne();
        return selectedServer;
    }
}